package com.itheima.service.impl;

import com.itheima.exception.BizException;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.User;
import com.itheima.service.CategoryService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper  categoryMapper;
    @Override
    public void addCategory(Category category) {
        //校验分类名称是否重复
        int count = categoryMapper.getCountName(category.getCategoryName());
        if (count > 0){
            throw new BizException("该分类已经存在");
        }
        User user = ThreadLocalUtil.get();
        category.setCreateUser(user.getId());
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        int i = categoryMapper.addCategory(category);
        System.out.println(i);
    }

    @Override
    public List<Category> findListByCreateUser() {


        User user  = ThreadLocalUtil.get();
        List<Category> list = categoryMapper.findListByCreateUser(user);

        return list;
    }

    @Override
    public void updateCategory(Category category) {

        category.setUpdateTime(LocalDateTime.now());
        int count = categoryMapper.getCountName(category.getCategoryName());
        if (count > 0){
            throw new BizException("该分类已经存在");
        }
        int i = categoryMapper.updateCategory(category);


    }

    @Override
    public Category getById(Integer id) {
        return categoryMapper.getbyId(id);
    }

    @Override
    public void deleteCategory(Integer id) {
        categoryMapper.deleteCategory(id);
    }
}
